﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Runtime.CompilerServices;
using Telerik.Web.Mvc;
using FluentValidation.Mvc;
using FluentValidation;
using Microhard.Core.DBUtility;
using Microhard.Core;
using Microhard.Core.Core;
using Microhard.Framework.MVCHelper;
using Microhard.Core.Algorithm;
using Microhard.Permission.MVCFilter;

namespace Microhard.Permission.Interface
{
    /// <summary>
    /// 基础Controller
    /// 程琳 2012-11-1
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// 泛型约束 new() 确保可以使用new T() http://blog.163.com/ccliushou@126/blog/static/123819096201191493859324/
    public class MicroHardBaseController<T> : Controller, IMicroHardControllerOperations<T> where T : new()
    {
        /// <summary>
        /// 接口集成实现
        /// </summary>
        protected IRepository<T> _repository;
        /// <summary>
        /// 在首页是否分页
        /// </summary>
        protected bool _isUsingPagingInIndex = true;

        #region IMicroHardControllerOperations<T> Members

        /// <summary>
        /// 列表页面
        /// </summary>
        /// <returns></returns>
        [MVCFilterAtrForLogon]//登录验证
        [MVCFilterAtrForResourcePermission]//功能权限验证
        [MVCFilterAtrForDataPermission]//数据权限验证
        public virtual ActionResult Index(ScopeResult scope)
        {
            int totalCount;
            IEnumerable<T> rtn = null;
            GridModel gm = new GridModel();

            _repository.scope = scope;
            if (_isUsingPagingInIndex)
            {
                rtn = _repository.Query(new T(), 1, 10, out totalCount);
                gm.Total = totalCount;
            }
            else
            {
                T model = new T();
                rtn = _repository.Query(model);
            }

            gm.Data = rtn;
            return View(gm);
        }

        /// <summary>
        /// 添加页面
        /// </summary>
        /// <returns></returns>
        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission]//功能权限验证
        [MVCFilterAtrForDataPermission]//数据权限验证
        public virtual ActionResult Create()
        {
            var model = new T();
            return View(model);
        }

        /// <summary>
        /// 添加方法
        /// </summary>
        /// <param name="model"></param>
        /// <param name="continueEditing"></param>
        /// <returns></returns>
        [HttpPost]
        [ParameterBasedOnFormNameAttribute("save-continue", "continueEditing")]
        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission(OperationKeyName = "Create")]//功能权限验证
        [MVCFilterAtrForDataPermission]//数据权限验证
        public virtual ActionResult SaveCreate([CustomizeValidator(RuleSet = "Insert")]T model, bool continueEditing, ScopeResult scope)
        {
            if (ModelState.IsValid)
            {
                _repository.scope = scope;
                var rtn = _repository.Add(model);
                rtn.ExecutedModel = model;
                this.HttpContext.Items["executedResult"] = rtn;

                if (!rtn.IsSucceed)
                {
                    StringBuilder errorMsg = new StringBuilder();
                    foreach (var err in rtn.ErrorMsg)
                    {
                        errorMsg.Append(err.Value);
                    }
                    ModelState.AddModelError("SaveFailure", errorMsg.ToString());
                    RedirectToAction("Create");
                }
                else
                {
                    if (continueEditing)
                        model = new T();
                    return continueEditing ? RedirectToAction("Create") : RedirectToAction("Index");
                }
            }
            return View("Create", model);
        }

        /// <summary>
        /// 修改页面
        /// </summary>
        /// <param name="identity"></param>
        /// <returns></returns>
        [HttpPost]
        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission]//功能权限验证
        [MVCFilterAtrForDataPermission]//数据权限验证
        public virtual ActionResult Update(Guid identity, ScopeResult scope)
        {
            ViewData["isUpdate"] = true;
            var model = _repository.GetModelByID(identity);
            return View(model);
        }


        [HttpPost]
        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission(OperationKeyName = "Update")]//功能权限验证
        [MVCFilterAtrForDataPermission]//数据权限验证
        public ActionResult UpdateByModel(T model)
        {
            ViewData["isUpdate"] = true;
            var updateModel = _repository.GetModelByModel(model);
            return View(updateModel);
        }

        /// <summary>
        /// 修改方法
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission(OperationKeyName = "Update")]//功能权限验证
        [MVCFilterAtrForDataPermission]//数据权限验证
        public virtual ActionResult SaveUpdate([CustomizeValidator(RuleSet = "Update")]T model, ScopeResult scope)
        {
            if (ModelState.IsValid)
            {
                _repository.scope = scope;
                var rtn = _repository.Update(model);
                if (rtn.IsSucceed)
                {
                    return RedirectToAction("Index");
                }
                else
                {
                    StringBuilder errorMsg = new StringBuilder();
                    foreach (var err in rtn.ErrorMsg)
                    {
                        errorMsg.Append(err.Value);
                    }
                    ModelState.AddModelError("SaveFailure", errorMsg.ToString());
                }
            }
            return View("Update", model);
        }

        /// <summary>
        /// 删除方法
        /// </summary>
        /// <param name="identities"></param>
        /// <returns></returns>
        [HttpPost]
        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission]//功能权限验证
        [MVCFilterAtrForDataPermission]//数据权限验证
        public virtual ActionResult Delete(List<Guid> identities, ScopeResult scope)
        {
            _repository.scope = scope;
            var result = _repository.Delete(identities);
            if (result.IsSucceed)
            {
                this.HttpContext.Items["ToDeleteIds"] = identities;
                return new JsonResult { Data = "succeed" };
            }
            return new JsonResult { Data = result.ErrorMsg.First().Value };
        }

        [HttpPost]
        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission(OperationKeyName = "Delete")]//功能权限验证
        [MVCFilterAtrForDataPermission]//数据权限验证
        public virtual ActionResult DeleteSingle(List<T> models, ScopeResult scope)
        {
            _repository.scope = scope;
            List<ExecutedResult> errors = new List<ExecutedResult>();
            List<Guid> forDelete = new List<Guid>();
            foreach (var del in models)
            {
                var result = _repository.Delete(del);
                if (!result.IsSucceed)
                {
                    errors.Add(result);
                }
                else
                {
                    forDelete.Add(result.Scope.PKID);
                }
            }
            if (errors.Count == 0)
            {
                this.HttpContext.Items["ToDeleteIds"] = forDelete;
                return new JsonResult { Data = "succeed" };
            }
            else
            {
                StringBuilder errorMsg = new StringBuilder();
                foreach (var e in errors)
                {
                    errorMsg.AppendLine(e.ErrorMsg.First().Value);
                }
                return new JsonResult { Data = errorMsg.ToString() };
            }
        }

        /// <summary>
        /// Grid分页调用
        /// </summary>
        /// <param name="command"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost, GridAction(EnableCustomBinding = true)]
        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission(OperationKeyName = "Index")]//功能权限验证
        [MVCFilterAtrForDataPermission(OnExecutingFilterDataType = "index", OnExecutedFilterDataType = "index")]//数据权限验证
        public virtual ActionResult _List(GridCommand command, T model, ScopeResult scope)
        {
            _repository.scope = scope;
            int totalCount;
            var rtn = _repository.Query(model, command.Page, command.PageSize, out totalCount);

            var userModel = new GridModel()
            {
                Data = rtn,
                Total = totalCount
            };
            return new JsonResult
            {
                Data = userModel
            };
        }

        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission(OperationKeyName = "Index")]//功能权限验证
        [MVCFilterAtrForDataPermission(OnExecutingFilterDataType = "index", OnExecutedFilterDataType = "index")]//数据权限验证
        public virtual ActionResult _ListWithNoPaging(T model, ScopeResult scope)
        {
            _repository.scope = scope;
            var rtn = _repository.Query(model);
            var userModel = new GridModel()
            {
                Data = rtn
            };
            return new JsonResult
            {
                Data = userModel
            };
        }

        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission(OperationKeyName = "Create")]//功能权限验证
        [MVCFilterAtrForDataPermission(OnExecutingFilterDataType = "Create", OnExecutedFilterDataType = "Create")]//数据权限验证
        public virtual ActionResult CreateWithParams(T model)
        {
            return View("Create", model);
        }

        [MVCFilterAtrForLogon()]//登录验证
        [MVCFilterAtrForResourcePermission(OperationKeyName = "Index")]//功能权限验证
        [MVCFilterAtrForDataPermission(OnExecutingFilterDataType = "index", OnExecutedFilterDataType = "index")]//数据权限验证
        public virtual ActionResult _GetSingleModel(Guid id)
        {
            var rtn = _repository.GetModelByID(id);
            return new JsonResult
            {
                Data = rtn,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
        public virtual ActionResult _StartWorkFlow(List<Guid> approveWorkflowInstanceIds)
        {
            //List<ExecutedResult> errors = new List<ExecutedResult>();
            //IWorkflowApproveResult iwa = IoC.Resolve<IWorkflowApproveResult>();
            //foreach (var i in approveWorkflowInstanceIds)
            //{

            //    //流程审批，直接审批通过
            //    var rtn = iwa.Add(new ApproveWorkflow.Models.WorkflowApproveResultModel
            //    {
            //        DataID = i,
            //        TableName = this.Request.Url.ToString(),
            //        Status = (int)WorkflowResultStatus.Approve
            //    });

            //    if (!rtn.IsSucceed)
            //    {
            //        errors.Add(rtn);
            //    }
            //}
            //if (errors.Count == 0)
            //{
            //    return new JsonResult { Data = "succeed" };
            //}
            //else
            //{
            //    StringBuilder errorMsg = new StringBuilder();
            //    foreach (var e in errors)
            //    {
            //        errorMsg.AppendLine(e.ErrorMsg.First().Value);
            //    }
            //    return new JsonResult { Data = errorMsg.ToString() };
            //}
            return new JsonResult { Data = null };
        }
        #endregion


        
    }
}
